package com.redoor.app.stake.auth.configurer;

import com.redoor.app.stake.auth.model.BaseMenu;
import com.redoor.app.stake.auth.model.BaseUser;
import com.redoor.app.stake.auth.model.serviceModel.LoginUserBean;
import com.redoor.app.stake.auth.service.BaseMenuService;
import com.redoor.app.stake.auth.service.BaseUserService;
import com.redoornetwork.framework.datasource.util.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by wangjunlei on 2018/2/5.
 */
public class ShiroRealm extends AuthorizingRealm {

    @Bean
    public BaseUserService getBaseUserService() throws Exception {
        BaseUserService baseUserService = (BaseUserService) SpringContextUtil.getBean("BaseUserService");
        return baseUserService;
    }
    /**
     * 如果Shiro在此页面不能进行sping的Bean注入所以使用通过service的名称匹配(需要在Service后添加value='#{name}')
     * @Author zhangYiHang
     * @Date 2018/4/2 14:21
     * @Param
     */
    @Bean
    public BaseMenuService getBaseMenuService() throws Exception {
        BaseMenuService baseMenuService = (BaseMenuService) SpringContextUtil.getBean("BaseMenuService");
        return baseMenuService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //此处只能获取登录用户账号
        String loginName  = (String) principals.getPrimaryPrincipal();
        BaseUser user  = null;
        try {
            user = getBaseUserService().findByUsername(loginName);
            String userId = user.getUserid();
            List<String> permsList = null;
            // 系统管理员，拥有最高权限
            if (userId == "1") {
                List<BaseMenu> menuList = null;
                try {
                    menuList = getBaseMenuService().findAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                permsList = new ArrayList<>(menuList.size());
                for (BaseMenu menu : menuList) {
                    permsList.add(menu.getPerms());
                }
                permsList.add("only:admin");
            }
            else {
                permsList = getBaseMenuService().qryMenuPermByUseruuid(user.getUuid());
            }
            // 用户权限列表
            Set<String> permsSet = new HashSet<String>();
            for (String perms : permsList) {
                if (StringUtils.isEmpty(perms)) {
                    continue;
                }
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
            authorizationInfo.setStringPermissions(permsSet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        BaseUserService baseUserService = null;
        try {
            baseUserService = getBaseUserService();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        //UserInfo userInfo = userInfoService.findByUsername(username);

        LoginUserBean userInfo = baseUserService.findByUsername(username);
        if(userInfo == null){
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username, //用户名
                userInfo.getPassword(), //密码
                ByteSource.Util.bytes(username),//salt=username+salt
                getName()  //realm name
        );

        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("userSession", userInfo);
        return authenticationInfo;
    }

}
